import configparser
import os
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parent.parent


class Config:
    _instance = None
    _config = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Config, cls).__new__(cls)
            cls._load_config()
        return cls._instance

    @classmethod
    def _load_config(cls):
        config = configparser.ConfigParser()

        env = os.environ.get('APP_ENV', 'dev')
        file_name = PROJECT_ROOT / "config/" / f"config_{env}.ini"

        if not file_name.exists():
            raise FileNotFoundError(f"Configuration file {file_name} not found.")

        config.read(file_name, encoding='utf-8')
        cls._config = config

    @classmethod
    def get_section(cls, section):
        return cls._config[section]

    @classmethod
    def get(cls, section, key):
        if not cls._config.has_option(section, key):
            return None
        return cls._config.get(section, key)

    @classmethod
    def getboolean(cls, section, key):
        return cls._config.getboolean(section, key)

    @classmethod
    def getint(cls, section, key):
        return cls._config.getint(section, key)

    @classmethod
    def getfloat(cls, section, key):
        return cls._config.getfloat(section, key)

    @property
    def root_path(self) -> Path:
        return PROJECT_ROOT

    @property
    def test_resource_path(self) -> Path:
        return PROJECT_ROOT / "test/resource/"

    def set_langsmith_env(self):
        os.environ["LANGCHAIN_TRACING_V2"] = self.get("langsmith", "tracing")
        os.environ["LANGCHAIN_API_KEY"] = self.get("langsmith", "api_key")
        os.environ["LANGCHAIN_PROJECT"] = self.get("langsmith", "project")

    def set_langsmith_project(self, project: str):
        os.environ["LANGCHAIN_PROJECT"] = project


config = Config()
